package com.maiji.cloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.maiji.cloud.entities.login.Label;
import com.maiji.cloud.entities.login.UploadRecord;
import com.maiji.cloud.mapper.LabelMapper;
import com.maiji.cloud.request.ReqMetaData;
import com.maiji.cloud.response.*;
import com.maiji.cloud.response.login.LabelResData;
import com.maiji.cloud.response.login.UploadImageResData;
import com.maiji.cloud.service.LabelService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.service.UploadRecordService;
import com.maiji.cloud.utils.BaseService;
import com.maiji.cloud.utils.RedisUtil;
import com.maiji.cloud.utils.UUID_MD5;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class LabelServiceImpl extends ServiceImpl<LabelMapper, Label> implements LabelService {

    @Autowired
    private RedisTemplate<String, Object> maiji1RedisTemplate;
    @Autowired
    private LabelMapper labelMapper;
    @Autowired
    private UploadRecordService uploadRecordService;

    @Override
    public BaseDataResDto<List<LabelResData>> findAllLabelsBySource(String source, Integer listShow) {
        String redisKey = RedisUtil.getRedisKey(REDISNAMESPACE, source, listShow != null ? listShow.toString() : "null");
        List<LabelResData> labels = JSON.parseArray((String) maiji1RedisTemplate.opsForValue().get(redisKey), LabelResData.class);
        if (labels == null) {
            labels = labelMapper.findAllLabelBySource(source, listShow);
            if (labels == null && labels.size() == 0) return new BaseDataResDto<>(Status.ERROR);
            RedisUtil.setObject(maiji1RedisTemplate, redisKey, JSON.toJSONString(labels));
        }
        return new BaseDataResDto<List<LabelResData>>(Status.SUCCESS).setData(labels);
    }

    @Override
    public BaseMetaResDto<List<LabelResData>> findAllLabels(String source, Integer listShow, String name, ReqMetaData metaData) {
        EntityWrapper<Label> entityWrapper = new EntityWrapper<>();
        if (StringUtil.isNotBlank(name)) entityWrapper.like("name", name);
        if (StringUtil.isNotBlank(source)) entityWrapper.eq("source", source);
        if (listShow != null) entityWrapper.eq("list_show", listShow);
        entityWrapper.orderAsc(Arrays.asList("list_show", "order_no"));
        Page<Label> page = selectPage(new Page<>(metaData.getPage(), metaData.getSize()), entityWrapper);
        List<Label> labelList = page.getRecords();
        List<String> labelIds = labelList.parallelStream().map(Label::getUuId).collect(Collectors.toList());
        List<UploadRecord> uploadRecords = uploadRecordService.selectList(new EntityWrapper<UploadRecord>().in("belong_id", labelIds));
        List<LabelResData> labelResDataList = BaseService.dealWithOneToOne(labelList, "getUuId", LabelResData.class,
                "setLabelImage", uploadRecords, "getBelongId", UploadImageResData.class);
        ResMetaData resMetaData = new ResMetaData(page.getCurrent(), page.getSize(), page.getTotal());
        return new BaseMetaResDto<List<LabelResData>>(Status.SUCCESS).setData(labelResDataList).setResMetaData(resMetaData);
    }

    @Override
    public BaseDataResDto<Label> addEditLabel(Label label) {
        if (StringUtil.isNotBlank(label.getUuId())) {
            if (! updateById(label)) return new BaseDataResDto<>(Status.ERROR);
            uploadRecordService.updateForSet("belong_id = null", new EntityWrapper<UploadRecord>().eq("belong_id", label.getUuId()));
        } else {
            label.setUuId(UUID_MD5.getUUID());
            if (! insert(label)) return new BaseDataResDto<>(Status.ERROR);
        }
        if (StringUtil.isNotBlank(label.getImgId()))
            if (! uploadRecordService.updateById(new UploadRecord().setUuId(label.getImgId()).setBelongId(label.getUuId())))
                return new BaseDataResDto<>(Status.ERROR);
        Arrays.asList("null", "0", "1", "2", "3").parallelStream().forEach(listShow -> {
            String redisKey = RedisUtil.getRedisKey(REDISNAMESPACE, label.getSource(), listShow);
            maiji1RedisTemplate.delete(redisKey);
        });
        return new BaseDataResDto<Label>(Status.SUCCESS).setData(label);
    }

    @Override
    public Label findLabelBySourceName (String source, String name) {
        String redisKey = RedisUtil.getRedisKey(REDISNAMESPACE, source, name);
        Label label = (Label) maiji1RedisTemplate.opsForValue().get(redisKey);
        if (label != null) return label;
        Wrapper<Label> labelWrapper = new EntityWrapper<Label>()
                .eq("source", source)
                .eq("name", name);
        label = selectOne(labelWrapper);
        if (label == null) return null;
        RedisUtil.setObject(maiji1RedisTemplate, redisKey, label);
        return label;
    }

	@Override
	public List<Label> getLabelsByIds(List<String> list) {
		List<Label> listLabel = labelMapper.getLabelsByIds(list);
		return listLabel;
	}

}
